package com.bdqn.t320.ch12.controller;


import com.bdqn.t320.ch12.entity.Right;
import com.bdqn.t320.ch12.entity.Role;
import com.bdqn.t320.ch12.entity.User;
import com.bdqn.t320.ch12.service.RoleService;
import com.bdqn.t320.ch12.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {


    @Resource
    UserService userService;

    @Resource
    RoleService roleService;


    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/")
    public String index() {
        return "login";
    }

    @RequestMapping("/main")
    public String main() {
        return "main";
    }

    @RequestMapping("/dologin")
    public String dologin(String usrName, String usrPassword, HttpSession session, Model model) {
       /* User user = userService.findByUsrNameAndUsrPasswordBiz(usrName, usrPassword);
        if (user == null) {
            model.addAttribute("msg", "用户名密码错误");
            //return "redirect:login";
            return "login";
        } else {
            session.setAttribute("user", user);
            return "main";
        }*/
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(usrName, usrPassword);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);// 认证、登录
            // 认证( 登录) 成功
            User user = (User) subject.getPrincipal();
            Role role = user.getRole(); //如果一对多关联不是立即加载，则需要通过用户获取 如果一对多关联不是立即加载，则需要通过用户获取角色
            List<Right> rights = roleService.findRightsByRole(role);
            role.getRights().addAll(rights);
            session.setAttribute("user", user);
            return "redirect:/main";//建议重定向
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            model.addAttribute("msg", "用户名或密码错误，登录失败！");
            return "login";
        } catch (LockedAccountException e) {
            model.addAttribute("msg", "用户被禁用，登录失败！");
            return "login";
        } catch (AuthenticationException e) {
            model.addAttribute("msg", "认证异常，登录失败！");
            return "login";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        session.invalidate();
        return "redirect:login";
    }

    @RequestMapping(value = "/403")
    public Object unauthorized() {
        return "403";
    }
}
